<template>
    <div>
    <el-dialog title="监督指导" :visible.sync="isSupervisesOpen" width="50%" :before-close="closeDelDialog" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row :gutter="10" class="mb8" style="width:80%;margin:20px auto">
                <el-col :span="1.5">
                    <!--  -->
                    <el-button type="success" plain icon="el-icon-top" @click="handleAdd()"  v-hasPermi="['archive:supervision:supervisesNew:add']">保存</el-button>
                </el-col>
            </el-row>
            <el-row ref="refbut" style="width:80%;margin:0 auto">
                <el-col :span="24" class="df transf-title-row">

                    <el-form-item label="">
                        <span slot="label">
                            <em style="color:red"> * </em>
                            指导建议
                        </span>
                        <editor v-model="form.content" style="width: 100%" accept=".png, .jpg, jpeg" :isMaterialList="true"
                            :isMaterialListStyle="'2'" />
                    </el-form-item>
                </el-col>
                <el-col>
                    <el-form-item label="上传附件">
                        <!--           　<el-button class="upload_btn" size="medium" type="primary" icon="el-icon-upload">上传文件</el-button>-->
                        <div style="display: flex; flex-wrap: wrap; /* 允许子元素换行 */">
                            <el-button class="upload_btn" type="primary" icon="el-icon-upload"
                                v-if="fileMJ == undefined && isFbState" @click="uploadTap">上传文件</el-button>
                            <el-upload v-else class="upload-file-demo" action="上传的url" ref="uploadComp" :auto-upload="true"
                                :show-file-list='false' :on-change="handleChange" :disabled="loading" accept=""
                                :http-request="uploadFile" :file-list="fileList">
                                <div style="width: 100%; display: flex">
                                    <el-button :loading="loading" type="primary" icon="el-icon-upload">上传文件</el-button>
                                </div>
                            </el-upload>
                            <el-select v-if="isFbState" style="margin-left:10px;" v-model="fileMJ" placeholder="请选择文件密级"
                                @change="selectChange($event)">
                                <el-option v-for="(item, idx) in renyuanOptions" :key="idx" :label="item.dictLabel"
                                    :value="item.dictValue"></el-option>
                            </el-select>
                            <div v-for="item in uploadList" style="display: flex; margin-left: 1%;align-items: center;"
                                :key="item">
                                <span style="padding: 0 5px">{{ item.docName }}</span>
                                <p v-if="isFbState" style="border-bottom: 1px solid red;">
                                    <span v-for="(i, idx) in renyuanOptions" :key="idx">
                                        {{ item.mj == i.dictValue ? i.dictLabel : '' }}
                                    </span>
                                </p>
                                <el-button type="text" @click="onPreviewTap(item)" style="margin-left:10px">预览</el-button>
                                <el-button type="text" style="color: #ff0000" @click="deleteTap(item)">删除</el-button>
                            </div>
                        </div>
                    </el-form-item>


                </el-col>
            </el-row>



        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="successTap" v-hasPermi="['archive:supervision:supervisesNew:submit']">提交</el-button>
        </div>
    </el-dialog>


    <el-dialog :title="title" :visible.sync="open" width="45%" append-to-body>
      <!--
       文件预览
       1、修改添加文件预览istype="1"
       2、查看组件详情istype="2"
       -->
      <FilePreview v-if="item" :item="item" :istype="istype" :tenantCode="form.tenantCode"></FilePreview>
    </el-dialog>
    </div>
</template>
<script>
import { uploadFile, getUserMessage, uploadFileList, guidanceAdd, guidanceDetail, guidanceDeit,deleteFile} from "@/api/archive/supervision/supervisesNew/supervisesNew.js"
import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import FilePreview from "@/views/archive/supervision/supervises/filePreview";
export default {
    props: ['isSupervisesOpen', 'superviseRow'],
    components:{FilePreview},
    watch: {
        superviseRow: {
            handler(newVal) {
                guidanceDetail({ id: newVal.id }).then(res => {
                    console.log(res)
                    if (res.code == "200") {
                        if (res.data != undefined) {
                            this.jdzdDATA = res.data;
                            this.form = res.data;
                            this.getFileList();
                        } else {
                            
                            //获取ID
                            getUserMessage().then(response => {
                                this.form.id = response.data.id;
                            });
                            this.form.tenantCode = newVal.tenantCode;
                            this.form.tenantId = newVal.id;
                            this.form.tenantName = newVal.registeredUnit;
                            this.jdzdDATA = undefined
                        }
                    }
                })

            },
            immediate: true
        }
    },
    data() {
        return {
            loading: false,
            form: {
                id: undefined,
                content: undefined,
                tenantCode: undefined,
                tenantId: undefined,
                tenantName: undefined
            },
            rules: {
                suggestions: [
                    { required: true, message: "指导建议不能为空", trigger: "blur" }
                ]
            },
            renyuanOptions: [],//密级下拉列表
            isFbState: false,
            fileMJ: undefined,
            fileList: [],
            uploadList: [],
            jdzdDATA: undefined,//根据此字段判断是添加还是修改 ，如果有数据是修改 没有数据是添加
             // 预览标题
            title: '',
            open: false,
            item: '',
            istype: '1',
        }
    },
    created() {
        this.uploadList = []

        fbstat().then(res => {  //false=不是分保，true=是分保 
            this.isFbState = res.data
            if (this.isFbState) {
                //密级下拉列表
                getDicts_archive("MJ").then(res => { //人员密级
                    getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
                        var mjdata = [];
                        for (var i in resdata.data) {
                            for (var j in res.data) {
                                if (resdata.data[i].daMj == res.data[j].dictValue) {
                                    mjdata.push(res.data[j])
                                }
                            }
                        }

                        this.renyuanOptions = mjdata
                        console.log(this.renyuanOptions, "------------------------------------------")

                    })
                })
            }
        })
    },
    methods: {
        closeDelDialog() {
            this.$emit("closeDelDialogSupervises")
        },
        // 文件上传 - 文件选中后上传
        handleChange(file, fileList) {
            /* 自动上传改成true会导致重复触发，所以在handleChange上传文件*/
            //  防抖
            let length = fileList.length
            this.fileList = fileList
            this.maxLength = Math.max(length, this.maxLength)
            setTimeout(() => {
                if (length === this.maxLength) {
                    // 你的上传文件逻辑
                    this.$refs.uploadComp.submit();
                }
            }, 100)
        },
        uploadTap() {
            if (this.fileMJ == undefined) {
                this.$message.warning(`请选择密级`);
                return false
            }
        },
        //上传文件MJ类型的下拉框
        selectChange(event) {
            // this.uploadData["mj"] = this.fileMJ
        },
        //开始上传文件
        uploadFile(content) {
            this.file = content.file
            const formData = new FormData();
            formData.append("file", content.file);
            formData.append("id", this.form.id);
            if (this.isFbState) {
                formData.append("mj", this.fileMJ);
            }
            uploadFile(formData).then(response => {
                this.getFileList()
            })
        },

        getFileList() {
            uploadFileList({ guidanceId: this.form.id }).then(response => {
                this.uploadList = response.rows
            })
        },




        //保存建议
        handleAdd() {
            console.log(this.jdzdDATA)
            if (this.jdzdDATA != undefined) {  //修改
                this.form.state=0;
                guidanceDeit(this.form).then(res => {
                    this.$modal.msgSuccess("修改成功");
                    this.$emit("closeDelDialogSupervises")
                })
            } else {
                this.form.state=0;
                guidanceAdd(this.form).then(res => {
                    if (res.code == '200') {
                        this.$modal.msgSuccess("保存成功");
                        this.$emit("closeDelDialogSupervises")
                    }
                })
            }


        },

        //点击确定
        successTap(){
            if (this.jdzdDATA != undefined) {  //修改
                this.form.state=1;
                guidanceDeit(this.form).then(res => {
                    this.$modal.msgSuccess("修改成功");
                    this.$emit("closeDelDialogSupervises")
                })
            } else {
                this.form.state=1;
                guidanceAdd(this.form).then(res => {
                    if (res.code == '200') {
                        this.$modal.msgSuccess("保存成功");
                        this.$emit("closeDelDialogSupervises")
                    }
                })
            }
        },


        // 预览
        onPreviewTap(item) {
            this.title = item.docName
            this.open = true
            this.item = item
        },
        // 删除
        deleteTap(item) {
            this.$modal.confirm('是否确认删除名为"' + item.docName + '"的附件？').then(function () {
                return deleteFile(item.id);
            }).then(() => {
                this.getFileList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => { });
        },
    }
}
</script>